package cn.gson.crm.controller.graduation;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.io.FilenameUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.gson.crm.model.dao.ImagesDao;
import cn.gson.crm.model.dao.StudentDao;
import cn.gson.crm.model.dao.StudnetClassShadowDao;
import cn.gson.crm.model.dao.TeaemploymentDao;
import cn.gson.crm.model.entity.Images;
import cn.gson.crm.model.entity.JyTeaemployment;
import cn.gson.crm.model.entity.Student;
import cn.gson.crm.model.entity.StudnetClassShadow;
import cn.gson.crm.model.mapper.ClassesMapper;
import cn.gson.crm.model.mapper.TeaemploymentMapper;
import lombok.extern.log4j.Log4j;

/**
 * 毕业学员Controller
 * 
 * @author asus
 *
 */
@Controller
@RequestMapping("/teaemploy")
@Log4j
public class TeaemploymentController {
	/**
	 * 毕业学员Dao
	 */
	@Autowired
	private TeaemploymentDao teaDao;
	/**
	 * 学员Dao
	 */
	@Autowired
	private StudentDao stuDao;
	/**
	 * 图片Dao
	 */
	@Autowired
	private ImagesDao imgDao;
	/**
	 * 上传图片路径
	 */
	@Value("${upload.file}")
	private String uploadDir;
	/**
	 * 学员Mapper
	 */
	@Autowired
	private TeaemploymentMapper teaMapper;
	/**
	 * 学员影子Dao
	 */
	@Autowired
	private StudnetClassShadowDao scsDao;
	/**
	 * 班级Mapper
	 */
	@Autowired
	private ClassesMapper claMapper;

	/**
	 * 查询所有就业学员信息
	 * 
	 * @param teaemployment
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("teaemployment")
	@ResponseBody
	public Map<String, Object> teaemployment(
			@RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize,
			@RequestParam(name = "name", required = false) String name) {
		// 查询数据
		PageHelper.startPage(pageNum, pageSize);
		List<JyTeaemployment> pageData = teaMapper.teaemploymentList(name);
		PageInfo<JyTeaemployment> info = new PageInfo<>(pageData);
		// 组装返回结果
		Map<String, Object> obj = new HashMap<String, Object>(16);
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}

	@RequestMapping("graduations")
	@ResponseBody
	public Map<String, Object> graduation(
			@RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize,
			@RequestParam(name = "name", required = false) String name,
			@RequestParam(name = "stuType", required = false) String stuType,
			@RequestParam(name = "className", required = false) String className,
			@RequestParam(name = "classType", required = false) String classType) {
		// 查询数据
		PageHelper.startPage(pageNum, pageSize);
		List<Map<String,Object>> pageData = teaMapper.selectGraduation(name, stuType, className, classType);
		PageInfo<Map<String,Object>> info = new PageInfo<>(pageData);
		// 组装返回结果
		Map<String, Object> obj = new HashMap<String, Object>(16);
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}
	
	/**
	 * 打开添加或编辑窗口，并传入数据
	 * 
	 * @param model
	 * @return
	 */
	@GetMapping({ "addteaemployment", "addteaemployment/{id}" })
	public String addteaemployment(@PathVariable(name = "id", required = false) Long id, Model model) {
		if (id != null) {
			Map<String, Object> sel = teaMapper.selectOne(id);
			JyTeaemployment jy = teaDao.findOne(id);
			if (jy != null && sel != null) {
				model.addAttribute("sel", sel);
				model.addAttribute("jytea", jy);
			}
		}
		return "addteaemployment";
	}

	/**
	 * 下拉框（班级）
	 * 
	 * @return
	 */
	@RequestMapping("/getClassList")
	@ResponseBody
	public List<Map<String, Object>> getClassList() {
		List<Map<String, Object>> cls = teaMapper.selectAllClass();
		return cls;
	}

	/**
	 * 下拉框（学员姓名）
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/getStudentListByClass/{id}")
	@ResponseBody
	public List<Map<String, Object>> getStudentListByClass(@PathVariable("id") Long id) {
		List<Map<String, Object>> stu = teaMapper.selectClassStudent(id);
		return stu;
	}

	/**
	 * 模糊查询学员
	 * 
	 * @return
	 */
	@RequestMapping("/getStudentList")
	@ResponseBody
	public List<Map<String, Object>> getStudentList() {
		List<Map<String, Object>> stu = teaMapper.selectStudent();
		return stu;
	}
	
	/**
	 * 模糊查询学员
	 * 
	 * @return
	 */
	@RequestMapping("/selectStus")
	@ResponseBody
	public List<Map<String, Object>> selectStus() {
		List<Map<String, Object>> stu = teaMapper.selectStus();
		return stu;
	}

	/**
	 * 添加、编辑就业学员信息
	 * 
	 * @param jy
	 * @param br
	 * @return
	 */
	@PostMapping("/saveGraduation")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> saveGraduation(@Valid JyTeaemployment jy, BindingResult br,
			@RequestParam(defaultValue = "offer", required = false) String type,
			@RequestParam(name = "file", required = false) MultipartFile file) {
		Map<String, Object> obj1 = new HashMap<String, Object>(16);
		try {
			obj1.put("success", false);
			if (br.hasErrors()) {
				obj1.put("message", "校验失败！");
				obj1.put("erros", br.getFieldErrors());
				return obj1;
			} else {
				if (jy.getStudent() != null) {
					if (teaMapper.selectStudents(jy.getStudent().getId()) == null) {
						obj1.put("message", "请选择正确的学员!");
						return obj1;
					}
				}
				if (file.getOriginalFilename() != null && !"".equals(file.getOriginalFilename())) {
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
					String dateDir = sdf.format(new Date());

					// 获取文件后缀名
					String ext = FilenameUtils.getExtension(file.getOriginalFilename());
					String newFileName = UUID.randomUUID().toString() + "." + ext;
					String filePath = String.format("%s/%s/%s", uploadDir, type, dateDir);
					File fileDir = new File(filePath);
					if (!fileDir.exists()) {
						// 如果目录不存在，则创建出来
						fileDir.mkdirs();
					}
					Images img = new Images();
					img.setDelete(true);
					img.setImageType(file.getContentType());
					img.setModeType(type);
					img.setName(file.getOriginalFilename());
					img.setPath(String.format("%s/%s/%s", type, dateDir, newFileName));
					img.setSize(file.getSize());
					img.setSuffix(ext);
					img.setUploaddate(new Date());
					// 将图片路径保存到数据库
					imgDao.save(img);
					jy.setOffer(img);
					file.transferTo(new File(fileDir, newFileName));
				}
				Student s = stuDao.findOne(jy.getStudent().getId());
				s.setState("就业");
				jy.setStudent(s);
				jy.setDelete(true);
				teaDao.save(jy);
				obj1.put("success", true);
				return obj1;
			}
		} catch (Exception e) {
			log.error("添加失败！", e);
			obj1.put("message", "添加失败！");
		}
		return obj1;
	}

	/**
	 * 预览
	 */
	@GetMapping("/saveGraduation/**")
	@ResponseBody
	public void preview(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String path = request.getServletPath();
		log.info(path);
		path = path.replaceFirst("/teaemploy/saveGraduation/", uploadDir);
		ServletOutputStream os = response.getOutputStream();
		File f = new File(path);
		log.info(f);
		if (!f.exists()) {
			// 附件不存在的时候，直接返回404
			response.sendError(404);
			return;
		}
		// 创建一个输入流
		FileInputStream fis = new FileInputStream(f);
		// 每次读取的字节数
		byte[] b = new byte[2048];
		// 每次实际读取到的字节长度
		int len = 0;
		while ((len = fis.read(b)) > 0) {
			// 进入循环，表示读取到了字节
			// 读到多少，就写出多少
			os.write(b, 0, len);
		}

		fis.close();
	}

	/**
	 * 打回
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("delete/{id}")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> delete(@PathVariable("id") Long id) {
		Map<String, Object> obj = new HashMap<String, Object>(16);
		try {
			obj.put("success", false);
			Student jy;
			if (id != null && (jy = stuDao.findOne(id)) != null) {
				StudnetClassShadow s = new StudnetClassShadow();
				s.setShadowId(jy.getId());
				s.setShadowName(jy.getName());
				StudnetClassShadow scs = claMapper.selectstuid(s);
				scsDao.delete(scs);
				teaMapper.deleteStudentAndClass(jy.getId());
				teaMapper.updateDelete(jy.getId());
				obj.put("success", true);
			} else {
				obj.put("message", "此学员不存在！");
			}
		} catch (Exception e) {
			obj.put("message", "打回失败！");
		}
		return obj;
	}

	/**
	 * 归档
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("guidang/{id}")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> guidang(@PathVariable("id") Long id) {
		Map<String, Object> obj = new HashMap<String, Object>(16);
		try {
			obj.put("success", false);
			JyTeaemployment jy;
			if (id != null && (jy = teaDao.findOne(id)) != null) {
				teaMapper.updateState(jy.getStudent().getId());
				obj.put("success", true);
			} else {
				obj.put("message", "此学员不存在！");
			}
		} catch (Exception e) {
			obj.put("message", "归档失败！");
		}
		return obj;
	}
	/**
	 * 统计图
	 * @param model
	 * @return
	 */
	@GetMapping("getcount")
	public String getTimeCount(Model model) {
		List<Map<String, Object>> count = new ArrayList<>(16);
		String[] month = {"01","02","03","04","05","06","07","08","09","10","11","12"};
		String[] address = {"株洲","上海","广州","其他"};
		
		for(int i=0;i<month.length;i++) {
			Map<String,Object> c=new HashMap<>();
			for(int j=0;j<address.length;j++) {
				Integer t = teaMapper.selectCount(month[i], "%"+address[j]+"%");
				c.put(address[j], t);
			}
			count.add(c);
		}
		Integer nan = teaMapper.selectGender("男");
		Integer nv = teaMapper.selectGender("女");
		model.addAttribute("count", count);
		model.addAttribute("nan", nan);
		model.addAttribute("nv", nv);
		return "statistics";
	}
	@RequestMapping("batchto")
	public String bacthto() {
		return "batchsave";
	}
	
	@RequestMapping("batch/{ids}")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public Map<String,Object> saveBatch(@PathVariable("ids") Long[] ids) {
		Map<String, Object> obj=new HashMap<>(16);
		obj.put("success", false);
		System.out.println(ids);
		if(ids.length == 0) {
			obj.put("message", "校验失败！");
		} else {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				for (int i = 0; i < ids.length; i++) {
					System.out.println(ids[i]);
					teaMapper.insertStu(true, sdf.format(new Date()),ids[i]);
					Student s = stuDao.findOne(ids[i]);
					s.setState("就业");
					stuDao.save(s);
				}
				obj.put("success", true);
			}
		
		return obj;
	}
	
}
